package com.waitingsnow.core.base
{
import com.waitingsnow.core.debug.LogOutput;
import com.waitingsnow.core.debug.Logger;
import com.waitingsnow.core.debug.States;

import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.external.ExternalInterface;
import flash.system.Capabilities;
import flash.utils.clearInterval;
import flash.utils.setTimeout;

/**
 * 
 * @author waitingsnow
 * $Id: BaseSprite.as 2 2012-05-17 10:10:03Z cgslendy@gmail.com $
 */
public class BaseSprite extends Sprite
{
	//==========================================================================
	//  Constructor
	//==========================================================================
	/**
	 * Constructs a new <code>BaseSprite</code> instance.
	 * 
	 */
	public function BaseSprite()
	{
		if (stage)
		{
			initContent();
		}
		else
		{
			addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
		}
	}
	
	//==========================================================================
	//  Variables
	//==========================================================================
	private var intervalID:int;
	private var logOutPut:LogOutput;
	
	//==========================================================================
	//  Methods
	//==========================================================================
	private function initContent():void
	{
		var playerType:String = Capabilities.playerType;
		if (playerType == "ActiveX" || playerType == "PlugIn")
		{
			checkJS();
		}
		else
		{
			initDisplay();
		}
	}
	
	private function checkJS():void
	{
		try
		{
			ExternalInterface.call("function getHref(){return document.location.href;}");
		}
		catch (error:Error)
		{
			clearInterval(intervalID);
			intervalID = setTimeout(checkJS, 50);
			return;
		}
		clearInterval(intervalID);
		initDisplay();
	}
	
	protected function initDisplay():void
	{
		initSystemSet();
	}
	
	protected function initSystemSet():void
	{
		stage.align = StageAlign.TOP_LEFT;
		stage.scaleMode = StageScaleMode.NO_SCALE;
		stage.quality = StageQuality.HIGH;
	}
	
	protected function initDebugInfo(debug:Boolean = false):void
	{
		if (!logOutPut)
		{
			logOutPut = new LogOutput();
			addChild(logOutPut);
			removeChild(logOutPut);
		}
		logOutPut.logLevel = debug ? Logger.LEVEL_DEBUG : Logger.LEVEL_INFO;
		if (debug)
		{
			addChild(new States());
		}
	}
	
	//==========================================================================
	//  Event Handlers
	//==========================================================================
	private function addedToStageHandler(event:Event):void
	{
		removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
		initContent();
	}
}
}